package com.contain2.abstractcontain.demo1;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 为了创建只读的Map，可以继承AbstractMap并实现entrySet()，为了创建只读的Set，可以继承AbstractSet并实现iterator
 * ()和size()。 设计模式：享元。 在需要过多的对象，或者产生普通对象太占用空间时使用享元。
 * 
 * @author Administrator
 *
 */
public class FlyweightMap extends AbstractMap<String, String> {

	@Override
	public Set<java.util.Map.Entry<String, String>> entrySet() {
		// TODO Auto-generated method stub
		Set<Map.Entry<String, String>> entries = new EntrySet(
				Countries.DATA.length);
		return entries;
	}

	private static class Entry implements Map.Entry<String, String> {
		int index;

		Entry(int index) {
			this.index = index;
		}

		public boolean equals(Object o) {
			return Countries.DATA[index][0].equals(o);
		}

		@Override
		public String getKey() {
			// TODO Auto-generated method stub
			return Countries.DATA[index][0];
		}

		@Override
		public String getValue() {
			// TODO Auto-generated method stub
			return Countries.DATA[index][1];
		}

		@Override
		public String setValue(String value) {
			// TODO Auto-generated method stub
			throw new UnsupportedOperationException();
		}

		public int hashCode() {
			return Countries.DATA[index][0].hashCode();
		}
	}

	public static class EntrySet extends AbstractSet<Map.Entry<String, String>> {
		private int size;

		EntrySet(int size) {
			this.size = size < 0 ? 0 : size;
		}

		private class Iter implements Iterator<Map.Entry<String, String>> {
			private Entry entry = new Entry(-1);

			@Override
			public boolean hasNext() {
				// TODO Auto-generated method stub
				return entry.index < size - 1;
			}

			@Override
			public java.util.Map.Entry<String, String> next() {
				// TODO Auto-generated method stub
				entry.index++;
				return entry;
			}

			@Override
			public void remove() {
				// TODO Auto-generated method stub
				throw new UnsupportedOperationException();
			}

		}

		@Override
		public Iterator<java.util.Map.Entry<String, String>> iterator() {
			// TODO Auto-generated method stub
			return new Iter();
		}

		@Override
		public int size() {
			// TODO Auto-generated method stub
			return size;
		}

	}

}
